/*
 * Copyright (C) 2001-2005 Pleasant nightmare studio
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.pleasantnightmare.gblade.io;

import com.jmex.bui.BComponent;
import com.jmex.bui.BContainer;
import org.pleasantnightmare.gblade.data.ComponentData;
import org.pleasantnightmare.gblade.data.ComponentType;

import java.util.HashSet;
import java.util.Set;

/**
 * Transfers between custom data classes to BUI components.
 *
 * @author deus
 * @version 1.0
 * @since Sep 9, 2009 12:10:55 PM
 */
public final class Data2GBui {
  private static Data2GBui INSTANCE;

  public static BComponent buildBui(ComponentData data) {
    if (INSTANCE == null)
      INSTANCE = new Data2GBui();

    return INSTANCE.buildComponent(data);
  }


  private Set<BComponentBuilder> builders;

  private Data2GBui() {
    builders = new HashSet<BComponentBuilder>();
    initBuilders();
  }

  private void initBuilders() {
    // TODO implement me
    throw new IllegalStateException("WAITING TO BE IMPLEMENTED!");
  }

  private BComponent buildComponent(ComponentData data) {
    // Simple checks for valid data
    if (data == null)
      throw new IllegalArgumentException("data = null");
    if (ComponentType.UNDEFINED.equals(data.getComponentType()))
      throw new IllegalStateException("Cannot have component of type UNDEFINED; " + data);

    // Build component
    BComponent component = null;
    for (BComponentBuilder builder : builders) {
      if (builder.getType().equals(data.getComponentType()))
        component = builder.build(data);
    }

    // Check if component was actually built (ie. the type is known to us)
    if (component == null)
      throw new IllegalStateException("Unknown component type encountered; " + data);

    // Check if we need to build any children, and recursively descend using this same method
    if (data.getChildren() != null)
      for (ComponentData childComponentData : data.getChildren()) {
        BComponent childComponent = buildComponent(childComponentData);
        ((BContainer) component).add(childComponent);
      }

    return component;
  }
}
